layui.define(['config', 'crypto', 'layer'], function (exports) {
    var tools = {};
    var CryptoJS = layui.crypto;
    var config = layui.config;
    $(function () {
        //ajax 全局异常处理
        $.ajaxSetup({
            error: function (jqXHR, textStatus, errorThrown) {
                switch (jqXHR.status) {
                    case(500):
                        layer.msg("系统异常，请联系管理员");
                        break;
                    case(401):
                        config.removeToken();
                        location.replace('login.html');
                        break;
                    case(403):
                        layer.msg("无权限执行此操作");
                        break;
                    case(408):
                        layer.msg("请求超时");
                        break;
                    default:
                        tools.log('ajax' + jqXHR.status);
                }
            }
        });
        //触发click事件
        $('.layui-body').on('click', '[data-method]', function () {
            var othis = $(this), method = othis.data('method'), methodObj = othis.data('method-obj') || 'methods';
            eval(methodObj + "[method] ?" + methodObj + "[method].call(this, othis) : ''");
        });
    });
    (function (t) {
        //原版ajax
        t.originAjax = $.ajax;
        $.ajax = function (obj) {
            if (obj.contentType === false) {
                return t.originAjax(t.buildAjaxHeader(obj));
            }
            //var params = $.extend({}, $.ajaxSettings, obj);
            //url处理
            var url = obj.url + "";
            var reg = /^(https?|ftp):\/\/.+$/;
            if (!reg.test(url) && url.indexOf("/") == 0) {
                /** /a/b/c类似的格式就追加前缀 */
                url = config.base_server + url;
            }
            if ($.isPlainObject(obj.urlParams)) {//将数据追加到url后
                if (url.indexOf("?") == -1) {
                    url += "?";
                }
                for (var key in obj.urlParams) {
                    url += key + "=" + encodeURIComponent(obj.urlParams[key]) + "&";
                }
                url = url.substring(0, url.length - 1);
            }
            //通用参数（header中）
            obj = t.buildAjaxHeader(obj);
            var type = (obj.type ? obj.type : (obj.method || 'GET')).toUpperCase();
            //构造请求参数
            var params = {
                type: type,
                url: url,
                async: obj.async && true,
                data: obj.data || obj.params,
                contentType: obj.contentType || $.ajaxSettings.contentType,
                dataType: obj.dataType || $.ajaxSettings.dataType, /**预期服务器返回的数据类型*/
                headers: obj.headers,
                success: function (res) {
                    if (typeof obj.success == 'function') {
                        if (0 == res.code && 'string' == res.attr1 && res.data) {
                            res.data = JSON.parse(res.data);
                        }
                        obj.success(res);
                    }
                },
                error: obj.error
            }
            params.data = $.isPlainObject(params.data) && params.type == 'GET' ? params.data : JSON.stringify(params.data);
            tools.log('tools提交ajax参数：' + JSON.stringify(params))
            return t.originAjax(params);
        }
        t.buildAjaxHeader = function (obj) {
            obj.headers = obj.headers || {};
            var isToken = obj.headers['isToken'] === false;
            var token = config.getToken()['access_token'];
            if (token && !isToken) {
                obj.headers['Authorization'] = 'Bearer ' + token// token
            }
            return obj;
        }
        /**解析返回数据*/
        t.parseData = function (res) {
            if (0 == res.code && 'string' == res.attr1 && res.data) {
                res.data = JSON.parse(res.data);
            }
            return res;
        }
        t.request = function (params) {
            params.contentType = params.contentType || "application/json;charset=UTF-8";
            params.dataType = params.dataType || "json";
            return $.ajax(params);
        };
        t.post = (params => {
            params.contentType = params.contentType || "application/x-www-form-urlencoded;charset=UTF-8";
            return $.ajax(params);
        })
        t.postJSON = function (obj) {
            obj.method = 'post';
            return tools.request(obj);
        }
        t.putJSON = function (obj) {
            obj.method = 'put';
            return tools.request(obj);
        }
        t.deleteJSON = function (obj) {
            obj.method = 'delete';
            return tools.request(obj);
        }
        t.getJSON = function (obj) {
            obj.method = 'get';
            return tools.request(obj);
        }
        /**字符串*/
        t.format = function () {
            if (arguments.length == 1) return arguments[0];
            for (var s = arguments[0], i = 1; i < arguments.length; i++)
                s = s.replace(new RegExp("\\{" + (i - 1) + "\\}", "g"), arguments[i]);
            return s;
        }
        t.strIsEmpty = function (str) {
            if (typeof str == "undefined" || str == null || str == "") {
                return true;
            } else {
                return false;
            }
        }
        /**
         *加密处理
         */
        t.encryption = function (params) {
            let {
                data,
                type,
                param,
                key
            } = params
            const result = JSON.parse(JSON.stringify(data))
            if (type === 'Base64') {
                param.forEach(ele => {
                    result[ele] = btoa(result[ele])
                })
            } else {
                param.forEach(ele => {
                    var data = result[ele]
                    key = CryptoJS.enc.Latin1.parse(key)
                    var iv = key
                    // 加密
                    var encrypted = CryptoJS.AES.encrypt(
                        data,
                        key, {
                            iv: iv,
                            mode: CryptoJS.mode.CBC,
                            padding: CryptoJS.pad.ZeroPadding
                        })
                    result[ele] = encrypted.toString()
                })
            }
            return result
        }

        /**
         * 跳转地址
         * @type {Function}
         */
        t.goto = (path => {
            window.location.href = path;
        });

        t.router = (path => {
            path = (path + '').indexOf('?') != -1 ? path : path + "?v=" + new Date().getTime()
            Q.go(path);
        })

        /**
         * 跳转到登陆页面
         */
        t.toLogin = function () {
            //获取当前的url地址
            debugger;
            var url = encodeURIComponent(location.href);
            if (tools.isDevLogin()) {
                tools.goto(tools.getRootPath(true) + "/login.html?redirect=" + url);
            } else {
                tools.goto(tools.getRootPath() + "/account/login.html?redirect=" + url);
            }
        }
        /**
         * 判断是否本地开发环境登陆
         * @returns {boolean}
         */
        t.isDevLogin = function () {
            return location.host.indexOf('localhost') != -1 || location.host.indexOf('127.0.0.1') != -1;
        }

        /**
         * 获取根路径
         * @returns {string}
         */
        t.getRootPath = function (hasProjectName) {
            var curWwwPath = window.document.location.href;
            var projectName = '';
            var pathName = window.document.location.pathname;
            var pos = curWwwPath.indexOf(pathName);
            var localhostPath = curWwwPath.substring(0, pos);
            if (hasProjectName) {
                projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
            }
            return (localhostPath + projectName);
        }
        /**
         * 获取请求参数
         * @param name
         * @returns {*}
         */
        t.getQueryString = function (name) {
            var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
            var r = window.location.search.substr(1).match(reg);
            if (r != null) {
                return unescape(r[2]);
            }
            return null;
        }

        /**
         * 重新加载页面
         * @type {Function}
         */
        t.reload = (res => {
            window.location.reload();
        })

        /**
         * 生成随机len位数字
         */
        t.randomLenNum = (len, date) => {
            let random = ''
            random = Math.ceil(Math.random() * 100000000000000).toString().substr(0, len || 4)
            if (date) random = random + Date.now()
            return random
        }

        /**
         * form 表单构造json数据
         * @param formId
         * @returns {{}}
         */
        t.serializeArray = function (formId) {
            formId = formId || "search-form";
            var o = {};
            var a = $("#" + formId).serializeArray();
            $.each(a, function () {
                if (o[this.name] !== undefined) {
                    if (!o[this.name].push) {
                        o[this.name] = [o[this.name]];
                    }
                    o[this.name].push(this.value || '');
                } else {
                    o[this.name] = this.value || '';
                }
            });
            return o;
        }


        /**打印日志*/
        t.log = (text) => {
            var flag = true;
            if (typeof config != 'undefined' && config.debug) {
                ;
            } else {
                flag = false;
            }
            if (flag) {
                console.log(text);
            }
        }

        // 缓存临时数据
        t.putTempData = function (key, value) {
            if (value) {
                layui.sessionData('tempData', {key: key, value: value});
            } else {
                layui.sessionData('tempData', {key: key, remove: true});
            }
        }
        // 获取缓存临时数据
        t.getTempData = function (key) {
            return layui.sessionData('tempData')[key];
        }
        //获取并且删除临时数据
        t.getAndDelTempData = function (key) {
            var data = tools.getTempData(key);
            tools.putTempData(key, null);//移除
            return data;
        }

        //初始化图标组件
        t.initIconComponent = function (path, fn) {
            var $iconInput = $(".icon-input");
            $iconInput.after('<div class="icon-input-content" style="display: none; height: 200px;position: absolute;overflow-y: auto;z-index: 99999;background-color:#ffffff ;border: 1px solid #ccc;border-top: none;"></div>')
            var $iconInputContent = $(".icon-input-content");
            $iconInputContent.load((path || 'public/pages/tpl/icons.html'), null, function () {
                var $iconLi = $iconInputContent.find("li.dib");
                $iconLi.click(function () {
                    if (typeof fn == 'function') {
                        fn(this);
                    } else {
                        var $this = $(this);
                        var $content = $this.parents('.icon-input-content');
                        $content.prev().val($this.find(".code-name").text());
                        $content.hide();
                    }
                });
            });
            $iconInput.focus(function () {
                $iconInputContent.show();
            })
            $(document).click(function (e) {
                var $target = $(e.target);
                if (!$target.hasClass('icon-input')) {
                    $iconInputContent.hide();
                }
            })
        }
    })(tools)
    exports('tools', tools);
})








